const express = require('express');
const axios = require('axios');
const path = require('path');
const fs = require('fs').promises;

const router = express.Router();

// 代理API请求
router.get('/api/proxy', async (req, res) => {
  try {
    const { url } = req.query;
    if (!url) {
      return res.status(400).json({ error: 'URL parameter is required' });
    }

    // 检查是否是本地API文档请求
    if (url.includes('/local/api/api-docs')) {
      const apiDocsPath = path.join(__dirname, '../api-docs.json');
      const apiDocsContent = await fs.readFile(apiDocsPath, 'utf8');
      const jsonData = JSON.parse(apiDocsContent);
      return res.json(jsonData);
    }

    const response = await axios.get(url, {
      headers: {
        'User-Agent': 'Swagger-Helper-App'
      }
    });

    // 检查响应内容类型
    const contentType = response.headers['content-type'];
    if (!contentType || !contentType.includes('application/json')) {
      console.error('Proxy error: Response is not JSON. Content-Type:', contentType);
      console.error('Response preview:', typeof response.data === 'string' ? response.data.substring(0, 200) : response.data);
      return res.status(400).json({ 
        error: 'The URL does not return valid JSON data',
        detail: 'Please check if the URL points to a valid OpenAPI/Swagger JSON document'
      });
    }

    res.json(response.data);
  } catch (error) {
    console.error('Proxy error:', error.message);
    if (error.response) {
      console.error('Response status:', error.response.status);
      console.error('Response headers:', error.response.headers);
      // 如果有响应内容且不是JSON，记录前200个字符
      if (error.response.data && typeof error.response.data === 'string') {
        console.error('Response preview:', error.response.data.substring(0, 200));
      }
    }
    res.status(500).json({ 
      error: 'Failed to fetch data from the provided URL',
      detail: error.message
    });
  }
});

router.get('/local/api/api-docs', async (req, res) => {
  console.log('Received request for /local/api/api-docs');
  try {
    const apiDocsPath = path.join(__dirname, '../api-docs.json');
    const apiDocsContent = await fs.readFile(apiDocsPath, 'utf8');
    res.setHeader('Content-Type', 'application/json');
    res.send(apiDocsContent);
  } catch (error) {
    console.error('Error reading api-docs.json:', error);
    res.status(500).json({ error: 'Failed to read API documentation file' });
  }
});

module.exports = router;